package meblog.online.server.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import meblog.online.server.utils.ThreadUtil;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static meblog.online.server.websocket.WebSocketConfig.*;

@Slf4j
@Component
public class WebSocketServer {

    public void Run() {
        EventLoopGroup boss = ThreadUtil.getEventLoop(BOSS_THREAD_NAME);
        EventLoopGroup worker = ThreadUtil.getEventLoop(WORKER_THREAD_NAME);
        try {
            ChannelFuture future = new ServerBootstrap()
                    .group(boss, worker)
                    .option(ChannelOption.SO_BACKLOG, BACKLOG)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new WSChannelInitializer())
                    .bind(PORT)
                    .sync();
            log.info("WS服务器启动......");
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("WS服务器发生异常: [{}]", e.getMessage(), e);
        } finally {
            log.info("WS服务器关闭......");
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

}
